package cn.edu.dlut.ssdut.foodCredit2012.service;

/*import java.util.List;

import org.hibernate.Query;*/
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.Customs;
import cn.edu.dlut.ssdut.foodCredit2012.model.CustomsCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class CustomsService {
	
	public void add(Customs c) throws Exception {
		if(!hasCustoms(c)){
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(c);
			session.getTransaction().commit();
		}
	}
	
	public void delete(Customs c) throws Exception {
		if(hasCustoms(c)){
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(c);
			session.getTransaction().commit();
		}
	}
	
	public void update (Customs c) {
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.update(c);
		session.getTransaction().commit();
	}
	
	/*public List customsList() {
		List customsList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Customs");
		query.setFirstResult(2);
		query.setMaxResults(10);
		customsList = query.list();
		
		session.getTransaction().commit();
		
		return customsList;
	}*/
	
	public boolean hasCustoms(Customs c) throws Exception {
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from Customs c where c.licenceID = :licenceID")
			.setString("licenceID", c.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public Customs load(Customs c) throws Exception{
		if(hasCustoms(c)){
			c = loadByLicenceID(c.getLicenceID());
			return c;
		}
		return c;
	}
	
	public Customs loadByLicenceID(String licenceID) throws Exception{
		Customs c = new Customs();
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		c = (Customs)session.createQuery("select c from Customs c where c.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		session.getTransaction().commit();
		return c;
	}
	
	public Customs customsCollectionToCostoms(CustomsCollection customsC) throws Exception{
		Customs c = new Customs();
		c.setBeginDate(customsC.getBeginDate());
		c.setChangeDate(customsC.getChangeDate());
		c.setCustomsID(customsC.getCustomsID());
		c.setEndDate(customsC.getEndDate());
		c.setLicenceID(customsC.getLicenceID());
		c.setReceiveDate(customsC.getReceiveDate());
		
		return c;
	}

}
